<template>
  <div class="app-container" v-loading="loading">
    <el-dialog :title="prop.title" :visible.sync="prop.open" width="680px" :close-on-click-modal="false" :show-close="false" destroy-on-close append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row v-if="!prop.isRoot">
          <el-col :span="24">
            <el-form-item label="上级组织机构">
              <Treeselect
                v-model="form.organizationParentId"
                :multiple="false"
                :options="parentTreeData"
                :flat="true"
                :normalizer="normalizer"
                placeholder="请选择适用组织"
                noOptionsText="无数据"
                @change="parentOrgChange"
              >
              </Treeselect>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="中文名称" prop="organizationName">
              <el-input v-model="form.organizationName" placeholder="请输入机构名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机构简称" prop="organizationShortName">
              <el-input v-model="form.organizationShortName" placeholder="请输入机构名称" />
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="机构编码" prop="organizationCode">
              <el-input v-model="form.organizationCode" placeholder="请输入机构编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="英文名称" prop="organizationEnglishName">
              <el-input v-model="form.organizationEnglishName" placeholder="请输入机构名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="机构类型" prop="organizationTypeId">
              <el-select v-model="form.organizationTypeId" placeholder="请选择机构类型">
                <el-option
                  v-for="item in orgTypes"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="虚拟机构" prop="organizationIsVirtual">
              <el-radio-group v-model="form.organizationIsVirtual">
                <el-radio v-for="item in switchData" :key="item.value" :label="item.value">{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="!prop.isRoot">
            <el-form-item label="机构负责人" prop="organizationPrincipalName">
              <el-select v-model="form.organizationPrincipalName" placeholder="请选择" filterable>
                <el-option-group
                  v-for="group in orgGroupPersons"
                  :key="group.organizationId"
                  :label="group.organizationName">
                  <el-option
                    v-for="item in group.directEmployees"
                    :key="item.employeeId"
                    :label="item.label"
                    :value="item.employeeName">
                  </el-option>
                </el-option-group>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-else>
            <el-form-item label="机构负责人" >
              <el-input v-model="form.organizationPrincipalName" placeholder="请输入负责人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否启用" prop="isEnable">
              <el-radio-group v-model="form.isEnable">
                <el-radio v-for="item in switchData" :key="item.value" :label="item.value">{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="saveLoading">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getList,add,edit,getDetail,getOrganizationPrincipalPersons,getOrganizationTypeSelectItems,checkNameIsUnique,checkCodeIsUnique} from '@/api/organization/organization/organization.js'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {organizationLevelTypes} from '@/utils/constants/common/constants.js'
export default {
  name: "OrganizationEdit",
  dicts: ['ministry_education_standard','organization_type'],
  components: {Treeselect},
  props:{
    prop:{
      type:Object,
      default:function(){
        return {
          title:'新增',
          level:null,
          parentId:null,
          editId:null,
          isRoot:false,
          open:false
        }
      }
    }
  },
  data() {
    var nameValidator = (rule, value, callback) => {
      if(value!==null&&value.trim()!==""){
        checkNameIsUnique({organizationName:value,organizationId:this.form.organizationId}).then(res =>{
          let isUnique = res.data
          if (isUnique) {
            return callback()
          }else{
            return callback(new Error('组织机构名称不能重复'));
          }
        })
      }else{
         return callback(new Error('组织机构名称不能为空'));
      }
    };
    var codeValidator = (rule, value, callback) => {
      if(value!==null&&value.trim()!==""){
        checkCodeIsUnique({organizationCode:value,organizationId:this.form.organizationId}).then(res =>{
          let isUnique = res.data
          if (isUnique) {
            return callback()
          }else{
            return callback(new Error('组织机构编码不能重复'));
          }
        })
      }else{
         return callback(new Error('组织机构编码不能为空'));
      }
    };
    return {
      saveLoading:false,
      open:this.prop.open,
      loading:false,
      isEdit:false,
      isLoadData:false,
      organizationLevelTypes:organizationLevelTypes,
      orgTypes:[],
      parentTreeData: [],
      orgGroupPersons:[],
      switchData:[
        {value:'1',label:'是'},
        {value:'0',label:'否'}
      ],
      // 表单参数
      form: {
        organizationParentId:this.prop.parentId,
        organizationLevel:this.prop.level,
        organizationName:null,
        organizationShortName:null,
        organizationEnglishName:null,
        organizationCode:null,
        organizationTypeId:null,
        organizationPrincipalId:null,
        organizationPrincipalName:null,
        organizationIsVirtual:'0',
        isEnable:'1',
      },
      // 表单校验
      rules: {
        organizationParentId: [
          { required: true, message: "请选择上级机构", trigger: "change" }
        ],
        organizationName: [
          { required: true, validator:nameValidator, trigger: "blur" }
        ],
        organizationTypeId: [
          { required: true, message: "机构类型不能为空", trigger: "blur" }
        ],
        organizationCode: [
          { required: true, validator:codeValidator, trigger: "blur" }
        ],
        organizationIsVirtual: [
          { required: true, message: "是否虚拟机构不能为空", trigger: "blur" }
        ],
        isEnable: [
          { required: true, message: "是否启用不能为空", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    normalizer(node) {
      return {
        id: node.organizationId,
        label: node.organizationName,
        children: node.children,
      }
    },
    //加载编辑时需要的前置数据
    getPreData(){
      let orgParentId = this.$props.prop.parentId
      let preMethods = [getList()]
      if(orgParentId !=='0'){
        preMethods.push(getOrganizationPrincipalPersons(orgParentId))
      }
      if(this.prop.editId!==null){
        this.isEdit = true
        preMethods.push(getDetail({organizationId:this.prop.editId}))
      }
      Promise.all(preMethods).then(resArr =>{
        //设置负责人下拉数据
        this.form.organizationParentId = orgParentId
        let parentTree = resArr[0].data
        if(orgParentId !=='0'){
          this.orgGroupPersons = resArr[1].data
        }
        //设置上级机构下拉数据
        this.parentTreeData = this.handleTree(parentTree, "organizationId","organizationParentId");
        //设置回显数据及组织机构类型下拉数据
        let typeParams = {orgLevel:0}
        if(this.isEdit){
          let editData = resArr[resArr.length-1].data
          this.form = {...editData}
          typeParams.orgLevel = Number.parseInt(this.form.organizationLevel)
        }else{
          typeParams.orgLevel = this.prop.level
        }
        //根据组织机构所在层级获取组织机构类型
        this.getorganizationTypeDatas(typeParams)
        //关闭加载中效果
        this.loading = false
        //数据加载完成后将标志位置为true
        this.isLoadData = true
      }).catch(err =>{
        this.loading = false
        //数据加载失败时将标志位置为true
        this.isLoadData = true
        console.log('查询组织机构编辑数据错误原因：',err)
      })
    },
    getorganizationTypeDatas(typeParams){
      if(typeParams.orgLevel < this.dict.type.organization_type.length){
        let tmp = this.dict.type.organization_type[typeParams.orgLevel]
        let tableName = tmp.value
        getOrganizationTypeSelectItems({tableName:tableName}).then(res =>{
          this.orgTypes = res.data
        }).catch(err =>{
          console.log('查询组织机构类型数据失败，原因：',err)
        })
      }
    },
    parentOrgChange(selected){
      console.log('changeSelect',selected)
      getOrganizationPrincipalPersons(selected).then(res =>{
        let orgPersonData = res.data
      }).catch(err =>{
        console.log('查询负责人下拉数据失败，原因：',err)
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.saveLoading = true
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.isEdit) {
            edit(this.form).then(response => {
              this.saveLoading = false
              this.$modal.msgSuccess("修改成功");
              this.cancel()
            }).catch(err =>{
              console.log('保存失败，原因：',err)
              this.saveLoading = false
            });
          } else {
            add(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.saveLoading = false
              this.cancel()
            }).catch(err =>{
              console.log('保存失败，原因：',err)
              this.saveLoading = false
            });
          }
        }else{
          this.saveLoading = false
        }
      });
    },
    // 表单重置
    reset() {
      this.form = {
        organizationParentId:null,
        organizationLevel:null,
        organizationName:null,
        organizationShortName:null,
        organizationEnglishName:null,
        organizationCode:null,
        organizationTypeId:null,
        organizationPrincipalId:null,
        organizationPrincipalName:null,
        organizationIsVirtual:'0',
        isEnable:'1',
      };
      this.isEdit = false
      this.isLoadData = false
    },
    // 取消按钮
    cancel() {
      this.$emit('close')
    },
  },
  mounted() {
    this.getPreData()
  },
};
</script>
<style scoped>

</style>
